package com.zzl.study.demo.tool;

import com.zzl.study.demo.dao.PoemRepository;
import com.zzl.study.demo.domain.Poem;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.List;

/**
 * 诗词工具服务
 *
 * @author: zhangzl
 * @date: 2025/10/13 15:22
 * @version: 1.0
 */
@Slf4j
public class PoemService {

    /**
     * 默认每次获取诗词数量
     */
    private static final int DEFAULT_FETCH_SIZE = 3;

    @Resource
    private PoemRepository poemRepository;

    /**
     * 获取指定作者的诗词
     *
     * @param author    作者名称
     * @param fetchSize 获取诗词条目数
     * @param page      分页当前页
     * @return 诗词列表
     */
    @Tool(name = "get_poems_by_author", description = "获取指定作者的诗词")
    public String getPoemsByAuthor(@ToolParam(description = "作者") String author, @ToolParam(description = "诗词条目数") int fetchSize, @ToolParam(description = "分页当前页，依次加1") int page) {
        if (fetchSize <= 0) {
            fetchSize = DEFAULT_FETCH_SIZE;
        }
        if (page < 0) {
            page = 1;
        }
        Pageable pageable = PageRequest.of(page - 1, fetchSize);
        log.debug("获取作者【{}】的诗词，条目数：{}，当前页：{}", author, fetchSize, page);
        List<Poem> poemList = this.poemRepository.findPoemsByAuthor(author, pageable);
        StringBuilder builder = new StringBuilder();
        builder.append("以下是作者 ").append(author).append(" 的诗词：\n");
        for (int count = 1; count <= poemList.size(); count++) {
            builder.append(count).append("、").append(poemList.get(count - 1)).append("\n").append("\n");
        }
        return builder.toString();
    }

    /**
     * 获取指定标签的诗词
     *
     * @param tag       tag名称
     * @param fetchSize 获取诗词条目数
     * @param page      分页当前页
     * @return 诗词列表
     */
    @Tool(name = "get_poems_by_tag", description = "获取关于指定标签的诗词")
    public String getPoemsByTag(@ToolParam(description = "指定标签") String tag, @ToolParam(description = "诗词条目数") int fetchSize, @ToolParam(description = "分页当前页，依次加1") int page) {
        if (fetchSize <= 0) {
            fetchSize = DEFAULT_FETCH_SIZE;
        }
        if (page < 0) {
            page = 1;
        }
        Pageable pageable = PageRequest.of(page- 1, fetchSize);
        log.debug("获取关于【{}】的诗词，条目数：{}，当前页：{}", tag, fetchSize, page);
        List<Poem> poemList = this.poemRepository.findPoemsByTag(tag, pageable);
        StringBuilder builder = new StringBuilder();
        builder.append("以下是关于 ").append(tag).append(" 的诗词：\n");
        for (int count = 1; count <= poemList.size(); count++) {
            builder.append(count).append("、").append(poemList.get(count - 1));
        }
        return builder.toString();
    }

}
